package com.lingxin.gps.wap.command;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.StrKit;
import com.lingxin.gps.sdk.GpsDeviceApi;
import com.pisces.core.Assert;
import com.pisces.core.BaseCommand;
import com.pisces.core.BizException;
import com.pisces.tool.query.QueryObject;

import java.util.regex.Pattern;

/**
 *
 */
public class CDeviceWeldList extends BaseCommand {

	private static final Pattern PATTERN_DATE_TIME = Pattern
			.compile("^(\\d{4})-(0\\d{1}|1[0-2])-(0\\d{1}|[12]\\d{1}|3[01]) (0\\d{1}|1\\d{1}|2[0-3]):[0-5]\\d{1}$");

	/**
	 * 设备号
	 */
	private String deviceCode;
	/**
	 * 开始时间
	 */
	private String startTime;
	/**
	 * 结束时间
	 */
	private String endTime;
	/**
	 * 焊接结果
	 */
	private Integer weldResult;
	/**
	 * 查询记录数
	 */
	private int size;
	/**
	 * 按焊接时间排序，1：顺序  2：逆序
	 */
	private int orderByWeldTime;

	private Long uid;
	private String token;

	@Override
	public void init() throws Exception {
		deviceCode = getPara("deviceCode");
		Assert.notBlank(deviceCode, "设备号不能为空");

		startTime = getPara("startTime");
		if (StrKit.notBlank(startTime) && !PATTERN_DATE_TIME.matcher(startTime).matches()) {
			throw new BizException("开始时间不正确");
		}

		endTime = getPara("endTime");
		if (StrKit.notBlank(endTime) && !PATTERN_DATE_TIME.matcher(endTime).matches()) {
			throw new BizException("结束时间不正确");
		}

		weldResult = getParaToInt("speed", null);
		size = getParaToInt("size");
		orderByWeldTime = getParaToInt("orderByWeldTime");

		uid = context.getAttr("uid");
		token = context.getAttr("token");
	}

	@Override
	public void doCommand() throws Exception {
		QueryObject queryObject = new QueryObject();
		if(StrKit.notBlank(startTime)){
			queryObject.addQuery("startTime", startTime);
		}
		if(StrKit.notBlank(endTime)){
			queryObject.addQuery("endTime", endTime);
		}
		if(weldResult != null){
			queryObject.addQuery("weldResult", weldResult);
		}
		if(size > 0){
			queryObject.addQuery("size", size);
		}
		if(orderByWeldTime > 0){
			queryObject.addQuery("orderByWeldTime", orderByWeldTime);
		}

		JSONObject resData = GpsDeviceApi.deviceWeldList(uid, token, deviceCode, queryObject);
		JSONArray weldList = resData.getJSONArray("weldList");
		Assert.moreThanZero(weldList.size(), "当前时段暂无焊接记录");
		data.put("weldList", weldList);

		data.put("deviceCode", deviceCode);
	}


}
